package com.mosai.alignpro.util;

import android.content.Context;
import android.view.Gravity;
import android.widget.Toast;

import java.lang.ref.WeakReference;

/**
 * Created by Rays on 2020/3/25.
 */
public final class ToastUtils {

    private static ToastUtils instance;
    private static WeakReference<Context> contextRef;
    private static Toast toast;

    public static ToastUtils getInstance() {
        if (instance == null) {
            synchronized (ToastUtils.class) {
                if (instance == null) {
                    instance = new ToastUtils();
                }
            }
        }
        return instance;
    }

    public static void init(Context context) {
        if (contextRef != null && contextRef.get() != null) {
            return;
        }
        contextRef = new WeakReference<>(context.getApplicationContext());
    }

    private ToastUtils() {

    }

    public void show(int resId) {
        Context context = getContext();
        if (context == null) {
            return;
        }
        show(context.getText(resId), context);
    }

    public void show(CharSequence text) {
        Context context = getContext();
        if (context == null) {
            return;
        }
        show(text, context);
    }

    private void show(CharSequence text, Context context) {
        if (toast != null) {
            toast.cancel();
        }
        toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public Context getContext() {
        if (contextRef == null) {
            return null;
        }
        return contextRef.get();
    }
}
